package cn.restcloud.example.controller.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.Cookie;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.Param;
import cn.restcloud.framework.core.annotation.rest.Params;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import cn.restcloud.framework.core.context.ServerContext;
import cn.restcloud.framework.core.util.ConfigUtil;
import cn.restcloud.framework.core.util.RequestUtil;
import cn.restcloud.framework.login.service.JwtTokenService;
import cn.restcloud.framework.login.service.LoginValidationService;
import cn.restcloud.framework.org.service.OrgPersonCacheUtil;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

@BeanConfig(appId = "core",beanId = "MyLoginRest",beanName = "用户登录获取token及token校验示例",beanType = BeanType.CONTROLLER,autowired = true,singleton = true,hotMode = true)
@RestConfig(url = "/rest/example")
public class MyLoginRest {
	
	@RestConfig(configName = "登录验证服务",method = "POST",url = "/login")
	@Params({ 
		@Param(id = "userName", name = "用户id",required=true),
		@Param(id = "password", name = "密码(md5加密后的32位字符串或者明文均可)",required=true)
	})
	public DocAndView loginValidate() throws Exception{
		//登录验证服务
		String userId=RequestUtil.getString("userName");
		String password=RequestUtil.getString("password");
		
		//进行用户名和密码验证,验证通过后生成一个token并返回
		String result=LoginValidationService.validation(userId, password);
		if(result.equals("ok")){ //这里可以进行自定义的用户名或密码验证
			DocAndView dv=ViewUtil.getJsonView();
			
			//用户登录成功，把用户的信息过行缓存
			OrgPersonCacheUtil.removePersonContextCacheByUserId(userId); //先清除一次缓存后，用户再次调用API时会再重新生成userContext对像
			
			//增加登录的cookie
			String identitytoken=JwtTokenService.getToken(userId,"","1"); //给此用户生成一个token
			List<Cookie> listCookie=new ArrayList<Cookie>();
			Cookie cookie = new Cookie(JwtTokenService.TOKENKEY, identitytoken);
			String cookieDomain=ConfigUtil.getConfig("CookieDomain");
			if(StringUtils.isNotBlank(cookieDomain)){
				cookie.setDomain(cookieDomain);
			}
			cookie.setPath("/");
			
			//增加用户cookie
			Cookie cookie2 = new Cookie("userName",userId); //写一个cookie到浏览器中
			cookie2.setDomain(cookieDomain);
			cookie2.setPath("/");
			
			listCookie.add(cookie);
			listCookie.add(cookie2);
			
			dv.setCookie(listCookie);
			dv.setResponseCode(302);
			dv.getResponseHeader().put("Location",ServerContext.getCurrentServerHost()+"/admin"); //用户登录成功后的重定向url
			return dv;
		}else{
			return ViewUtil.getErrorView(result,400);
		}
	}
	
	@RestConfig(configName = "根据userId生成一个token",method = "POST",url = "/token/create")
	@Params({ 
		@Param(id = "userId", name = "用户userId",required=true),
	})
	public DocAndView getToken(String userId) throws Exception{
		String token=JwtTokenService.getToken(userId);
		return ViewUtil.getJsonView(token);
	}
	
	@RestConfig(configName = "验证token是否有效",method = "POST",url = "/token/validate")
	@Params({ 
		@Param(id = "token", name = "要验证的token",required=true),
	})
	public DocAndView tokenValidate(String token) throws Exception{
		HashMap<String,String> userMap=JwtTokenService.checkTokenValid(token, "");
		if(userMap==null) {
			return ViewUtil.getErrorView("无效的token");
		}else {
			//token验证成功，返回一个json对像
			Document doc=new Document();
			doc.putAll(userMap);
			return ViewUtil.getJsonView(doc);
		}
	}
	
}
